<script setup lang="ts" name="SystemTenantForm">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { getIntDictOptions } from '@/utils/dict'
import { DICT_TYPE } from '@/enums/dictEnums'
import { TenantApi, TenantType } from '@/api/system/tenant'
import { TenantPackageApi, TenantPackageType } from '@/api/system/tenantPackage'
import { CommonStatusEnum } from '@/enums/commonEnums'
const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const visible = ref(false) // 弹窗的是否展示
const title = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined as number | undefined,
  name: '',
  contactName: '',
  contactMobile: '',
  domain: '',
  packageId: undefined as number | undefined,
  username: '',
  password: '',
  expireTime: undefined as Date | undefined,
  status: CommonStatusEnum.ENABLE,
  remark: ''
})
const formRules = reactive({
  name: [{ required: true, message: t('sys.tenant.rules', 'name'), trigger: 'blur' }],
  contactName: [{ required: true, message: t('sys.tenant.rules', 'contactName'), trigger: 'blur' }],
  contactMobile: [{ required: true, message: t('sys.tenant.rules', 'contactMobile'), trigger: 'blur' }],
  domain: [{ required: true, message: t('sys.tenant.rules', 'domain'), trigger: 'blur' }],
  packageId: [{ required: true, message: t('sys.tenant.rules', 'packageId'), trigger: 'blur' }],
  username: [{ required: true, message: t('sys.tenant.rules', 'username'), trigger: 'blur' }],
  password: [{ required: true, message: t('sys.tenant.rules', 'password'), trigger: 'blur' }],
  expireTime: [{ required: true, message: t('sys.tenant.rules', 'expireTime'), trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const packageList = ref([] as TenantPackageType[]) // 租户套餐

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  visible.value = true
  title.value = t('action', type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TenantApi.detail(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载套餐列表
  packageList.value = await TenantPackageApi.simple()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as TenantType
    if (formType.value === 'create') {
      await TenantApi.create(data)
      message.success(t('message', 'createSuccess'))
    } else {
      await TenantApi.update(data)
      message.success(t('message', 'updateSuccess'))
    }
    visible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined as number | undefined,
    name: '',
    contactName: '',
    contactMobile: '',
    domain: '',
    packageId: undefined as number | undefined,
    username: '',
    password: '',
    expireTime: undefined as Date | undefined,
    status: CommonStatusEnum.ENABLE,
    remark: ''
  }
  formRef.value?.resetFields()
}
</script>

<template>
  <Dialog v-model="visible" :title="title" width="600px">
    <el-form ref="formRef" v-loading="formLoading && systemConfig.loadingType === 'module'" :model="formData" :rules="formRules" label-width="80px">
      <el-form-item :label="t('sys.tenant', 'name')" prop="name">
        <el-input v-model="formData.name" clearable :placeholder="t('sys.tenant.rules', 'name')" />
      </el-form-item>
      <el-form-item v-if="!formData.id || (formData.id && formData.packageId !== 0)" :label="t('sys.tenant', 'packageId')" prop="packageId">
        <el-select v-model="formData.packageId" clearable :placeholder="t('sys.tenant.rules', 'packageId')">
          <el-option v-for="item in packageList" :key="item.id" :label="item.name" :value="item.id!" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="!formData.id || (formData.id && formData.packageId !== 0)" :label="t('sys.tenant', 'contactName')" prop="contactName">
        <el-input v-model="formData.contactName" clearable :placeholder="t('sys.tenant.rules', 'contactName')" />
      </el-form-item>
      <el-form-item v-if="!formData.id || (formData.id && formData.packageId !== 0)" :label="t('sys.tenant', 'contactMobile')" prop="contactMobile">
        <el-input v-model="formData.contactMobile" clearable :placeholder="t('sys.tenant.rules', 'contactMobile')" />
      </el-form-item>
      <el-form-item v-if="!formData.id || (formData.id && formData.packageId !== 0)" :label="t('sys.tenant', 'domain')" prop="domain">
        <el-input v-model="formData.domain" clearable :placeholder="t('sys.tenant.rules', 'domain')" />
      </el-form-item>
      <el-form-item :label="t('sys.tenant', 'username')" prop="username">
        <el-input v-model="formData.username" clearable :disabled="!!formData.id" :placeholder="t('sys.tenant.rules', 'username')" />
      </el-form-item>
      <el-form-item v-if="!formData.id" :label="t('sys.tenant', 'password')" prop="password">
        <el-input v-model="formData.password" clearable :placeholder="t('sys.tenant.rules', 'password')" />
      </el-form-item>
      <el-form-item v-if="!formData.id || (formData.id && formData.packageId !== 0)" :label="t('sys.tenant', 'expireTime')" prop="expireTime">
        <el-date-picker v-model="formData.expireTime" clearable :placeholder="t('sys.tenant.rules', 'expireTime')" type="datetime" :default-time="new Date('1 23:59:59')" value-format="YYYY-MM-DD HH:mm:ss" />
      </el-form-item>
      <el-form-item v-if="!formData.id || (formData.id && formData.packageId !== 0)" :label="t('common', 'status')" prop="status">
        <el-radio-group v-model="formData.status" class="radio-button">
          <el-radio-button v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)" :key="dict.value" :value="dict.value">
            {{ dict.label }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="t('common', 'remark')" prop="remark">
        <el-input v-model="formData.remark" clearable :placeholder="t('common.rules', 'remark')" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">{{ t('action', 'cancel') }}</el-button>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">{{ t('action', 'confirm') }}</el-button>
    </template>
  </Dialog>
</template>

<style scoped lang="scss">
.el-form{
  margin-right: -6px;
}
</style>
